using System;
using System.ComponentModel;

namespace Framework.Library.Core.Utils.Resources
{
    [AttributeUsage(AttributeTargets.All)]
    public abstract class ResourceDefaultValueAttribute : DefaultValueAttribute
    {
        private readonly Type _type;
        private bool _localized;
        private IResourceGetter _resourceLoader;

        public ResourceDefaultValueAttribute(string value)
            : base(value)
        {
        }

        public ResourceDefaultValueAttribute(Type type, string value)
            : base(value)
        {
            _type = type;
        }

        protected IResourceGetter ResourceLoader
        {
            get
            {
                if (_resourceLoader == null)
                    _resourceLoader = Create();

                return _resourceLoader;
            }
        }

        public override object TypeId
        {
            get { return typeof (DefaultValueAttribute); }
        }

        public override object Value
        {
            get
            {
                if (!_localized)
                {
                    _localized = true;
                    var resourceKey = (string) base.Value;

                    if (!string.IsNullOrEmpty(resourceKey))
                    {
                        object defaultValue = ResourceLoader.GetString("Default_" + resourceKey);

                        if (_type != null)
                        {
                            try
                            {
                                defaultValue =
                                    TypeDescriptor.GetConverter(_type).ConvertFromInvariantString((string) defaultValue);
                            }
                            catch (NotSupportedException)
                            {
                                defaultValue = null;
                            }
                        }

                        base.SetValue(defaultValue);
                    }
                }
                return base.Value;
            }
        }

        protected abstract IResourceGetter Create();
    }
}